package com.itheima.reggie_auto.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie_auto.common.R;
import com.itheima.reggie_auto.dto.DishDto;
import com.itheima.reggie_auto.entity.Dish;
import com.itheima.reggie_auto.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author 刘少宽
 * @since 2022-09-23
 */
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        dishService.save(dishDto);
        //删除缓存  --  全部删除
       /* //先获取所有的key
        String key = "dish_*";
        Set keys = redisTemplate.keys(key);
        //删除所有的key
        redisTemplate.delete(keys);*/

        //删除缓存---精准删除
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return R.success("添加菜品成功");
    }

    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, Dish dish){
        Page<DishDto> pageInfo = dishService.page(page,pageSize,dish);
        return R.success(pageInfo);
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getById(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.update(dishDto);

        //修改的时候必须全清空 ，因为他如果改的是菜品分类，则只会把改变后的菜品分类数据删除，改变前的数据并没有删除
         //先获取所有的key
        String key = "dish_*";
        Set keys = redisTemplate.keys(key);
        //删除所有key的数据
        redisTemplate.delete(keys);

        //删除缓存---精准删除
        /*String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);*/
        return R.success("修改菜品成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateByIds(@PathVariable Integer status,Long[] ids){

        dishService.updateByIds(status,ids);
        return R.success("修改状态成功");
    }

    @DeleteMapping
    public R<String> deleteByIds(@RequestParam("ids") List<Long> ids) {
        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> list = dishService.getByCategoryId(dish);
        return R.success(list);
    }


}

